const rp = require('request-promise-native');

// 引入config模块
const {
    appID,
    appsecret
} = require('../connfig');
//引入menu模块
const menu = require('./menu')
    //引入api模块
const api = require('../utlis/api')

//引入tool
const { writeFileAsync, readFileAsync } = require('../utlis/tool')

const { template_id, touser } = require('../connfig')


class Wechat {
    constructor() {

    }

    //用来获取access_token
    getAccessToken() {
        const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appsecret}`;
        return new Promise((resolve, reject) => {
            rp({
                    method: 'GET',
                    url,
                    json: true
                })
                .then(res => {
                    console.log(res);
                    res.expires_in = Date.now() + (res.expires_in - 300) * 1000;
                    resolve(res)
                })
                .catch(err => {
                    console.log(err);
                    reject('getAccessToken出了问题' + err)
                })
        })

    }
    saveAccessToken(accessToken) {
            return writeFileAsync(accessToken, 'accessToken.txt')
        }
        //用来读取access_token
    readAccessToken() {
            return readFileAsync('accessToken.txt')
        }
        //用来检测access_token是否有效
    isValidAccessToken(data) {
            if (!data && !data.access_token && !data.expires_in) {
                return false;
            }
            return data.expires_in > Date.now();
        }
        //用来获取没有过期的access_token
    fetchAccessToken() {
        if (this.access_token && this.expires_in && this.isValidAccessToken(this)) {
            return Promise.resolve({
                access_token: this.access_token,
                expires_in: this.expires_in
            })
        }
        return this.readAccessToken()
            .then(async res => {
                if (this.isValidAccessToken(res)) {
                    return Promise.resolve(res)
                } else {
                    const res = await this.getAccessToken();
                    await this.saveAccessToken(res);
                    return Promise.resolve(res)
                }
            })
            .catch(async err => {
                const res = await this.getAccessToken();
                await this.saveAccessToken(res);
                return Promise.resolve(res)
            })
            .then(res => {
                this.access_token = res.access_token;
                this.expires_in = res.expires_in;
                return Promise.resolve(res);
            })
    }



    //用来获取jsapi_ticket
    getTicket() {

            return new Promise(async(resolve, reject) => {
                const data = await this.fetchAccessToken()
                const url = `${api.ticket}&access_token=${data.access_token}`;
                // console.log(url);
                rp({
                        method: 'GET',
                        url,
                        json: true
                    })
                    .then(res => {

                        resolve({
                            ticket: res.ticket,
                            expires_in: Date.now() + (res.expires_in - 300) * 1000
                        })
                    })
                    .catch(err => {
                        reject('getTicket出了问题' + err)
                    })
            })

        }
        //用来保存jsapi_ticket
    saveTicket(ticket) {
            return writeFileAsync(ticket, 'ticket.txt')
        }
        //用来读取jsapi_ticket
    readTicket() {
            return readFileAsync('ticket.txt')
        }
        //用来检测jsapi_ticket是否有效
    isValidTicket(data) {
            if (!data && !data.ticket && !data.expires_in) {
                return false;
            }
            return data.expires_in > Date.now();
        }
        //用来获取没有过期的jsapi_ticket
    fetchTicket() {
        if (this.ticketn && this.ticket_expires_in && this.isValidTicket(this)) {
            return Promise.resolve({
                ticket: this.ticket,
                expires_in: this.expires_in
            })
        }
        return this.readTicket()
            .then(async res => {
                if (this.isValidTicket(res)) {
                    return Promise.resolve(res)
                } else {
                    const res = await this.getTicket();
                    await this.saveTicket(res);
                    return Promise.resolve(res)
                }
            })
            .catch(async err => {
                const res = await this.getTicket();
                await this.saveTicket(res);
                return Promise.resolve(res)
            })
            .then(res => {
                this.ticket = res.ticket;
                this.ticket_expires_in = res.expires_in;
                return Promise.resolve(res);
            })
    }




    //创建菜单
    createMenu(menu) {

        return new Promise(async(resolve, reject) => {
            try {
                const data = await this.fetchAccessToken()
                const url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${data.access_token}`;
                const result = await rp({
                    method: 'POST',
                    url,
                    json: true,
                    body: menu
                });
                resolve(result);
            } catch (e) {
                reject('createMenu方法出了问题' + e);
            }
        })
    };
    //删除菜单
    deleteMenu() {
        return new Promise(async(resolve, reject) => {
            try {
                const data = await this.fetchAccessToken();
                const url = `https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=${data.access_token}`;
                const result = await rp({
                    method: 'GET',
                    url,
                    json: true
                })
                resolve(result);
            } catch (e) {
                reject('deleteMenu方法出了问题' + e)
            }
        })
    };

    // getMokuai() {
    //     const sendDate = {
    //         touser,
    //         template_id,
    //         data: {
    //             nameData: {
    //                 value: '小贾'
    //             },
    //             dotaData: {
    //                 value: '2023/3/13'
    //             },
    //             beizhu: {
    //                 value: 'nicai'
    //             }
    //         }
    //     }
    //     return new Promise(async(resolve, reject) => {
    //         try {
    //             const data = await this.fetchAccessToken()
    //             const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${data.access_token}`;
    //             const mokaun = await rp({
    //                 method: 'POST',
    //                 url,
    //                 json: true,
    //                 body: sendDate
    //             });
    //             resolve(mokaun);
    //         } catch (e) {
    //             reject('  getMokuai方法出了问题' + e);
    //         }
    //     })
    // }
}


// 模拟测试
// w.fetchAccessToken()
(async() => {
    const w = new Wechat();
    let result = await w.deleteMenu()
        // console.log(result);
        //创建新的菜单
    result = await w.createMenu(menu)
        // console.log(result);
    w.fetchTicket();
    // let m = await w.getMokuai();
    // console.log(m);
})()

module.exports = Wechat;